package com.pzl.projection.push;

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetSocketAddress;

public class NetDispatcher {
    final String TAG = "jinx_projection";

    private WebSocket myWebSocket;
    private int port;
    private WebSocketServer webSocketServer;


    public NetDispatcher(int port) {
        this.port = port;
        this.webSocketServer = new WebSocketServer(new InetSocketAddress(port)) {
            @Override
            public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
                myWebSocket = webSocket;
                Log.i(TAG, "WebSocketServer onOpen [" + webSocket.getLocalSocketAddress().getHostName() + "] ");
            }

            @Override
            public void onClose(WebSocket webSocket, int i, String s, boolean b) {
                Log.i(TAG, "onClose: 关闭 socket ");
            }

            @Override
            public void onMessage(WebSocket webSocket, String s) {
                Log.i(TAG, "onMessage [" + webSocket.getLocalSocketAddress().getHostName() + "] : " + s);
            }

            @Override
            public void onError(WebSocket webSocket, Exception e) {
                Log.i(TAG, "WebSocketServer onError:  " + e.toString());
            }

            @Override
            public void onStart() {
                Log.i(TAG, "WebSocketServer onStart   ");
            }
        };


        webSocketServer.start();
    }

    public void sendData(byte[] bytes) {
        Log.i("sendData", "myWebSocket = null ：" + (myWebSocket == null ? "true" : "false"));
        if (myWebSocket != null && myWebSocket.isOpen()) {
            myWebSocket.send(bytes);
            Log.i("sendData", "myWebSocket 发送 ：" + bytes.length);
        }
    }


    public void close() {
        try {
            myWebSocket.close();
            webSocketServer.stop();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}
